var baseUrl='http://localhost:8081/cargo_agent//picture/getPictures/';
var userDatatable;
$(function () {
    userDatatableSource.init();
    createImg();
})
function downloadFile (url){
    const iframe = document.createElement("iframe");
    iframe.style.display = "none"; // 防止影响页面
    iframe.style.height = 0; // 防止影响页面
    iframe.src = url;
    document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
    // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
    setTimeout(()=>{
        iframe.remove();
    }, 5 * 60 * 1000);
}
function createImg() {

    /**
     * 重置
     */
    $("#m_reset").on("click", function () {
        $("#resetCN").val('');
    });

    /**
     * 查询
     */
    $("#m_search").on("click", function () {
        var param = {
            pictureName: $.trim($("input[name='cname']").val()),
        };
        queryMDatatable(userDatatable, param);
    });
    /**
     * 批量删除
     */
    $("#deleteBtn").on("click", function () {
        var ids = getMDatatableSelectedIds(userDatatable);
        if (ids.length === 0) {
            layer.msg('请勾选要删除的图片信息!', {
                icon: 0
            });
            return;
        }
        var pictureName = getMDatatableSelectedColumns(userDatatable, "pictureName");
        layer.confirm('确定批量删除<font color="red">[' + pictureName + ']</font>图片信息？', {
            icon: 3,
            title: '提示',
            btn: ['确定', '取消'] // 额
        }, function () {
            userDatatableSource.deleteById(ids.join(','));
        }, function (index) {
            layer.close(index);
        });
    });

    /**
     * 批量下载
     */
    $("#downLoadBtn").on("click", function () {
        var ids = getMDatatableSelectedIds(userDatatable);
        if (ids.length === 0) {
            layer.msg('请勾选要下载的图片信息!', {
                icon: 0
            });
            return;
        }
        var pictureName = getMDatatableSelectedColumns(userDatatable, "pictureName");
        $.each(pictureName, function (i) {
            userDatatableSource.download(pictureName[i].replaceAll(".", "!"));
        })
    });

}
/**
 * 表格列定义
 *
 * @type {*[]}
 */
var tableColumns = [
    {
        field: "id", title: "#", width: 20, textAlign: 'center',
        selector: {class: "m-checkbox--solid m-checkbox--brand"}
    },
    {
        field: "actions", title: "操作", width: 80, textAlign: 'center', titleHide: true, overflow: "visible",
        template: function (row) {
            var  button =  getColumnButton({
                clazz: 'm-btn--hover-danger',
                title: '删除', icon: 'la la-trash',
                click: "deleteByPrefixAndNo('" + row.id + "')"
            });
            button =button+ getColumnButton({
                clazz: 'm-btn--hover-accent editBtn',
                title: '编辑', icon: 'la la-edit',
                click: "EdiIt('" + row.id + "')"
            });

            return button;
        }
    },
    {field: "pictureName", title: "图片名字", textAlign: 'center', sortable: false},
    {field: "pictureDetail", title: "图片详情", textAlign: 'center', sortable: false,
        template: function (t) {
            return '<img src = "'+baseUrl+t.pictureName +' "+">"'+"</img>"
        }},
    {field: "pictureAddress", title: "图片保存地址", textAlign: 'center', sortable: false},
    {field: "optiorName", title: "操作人", textAlign: 'center', sortable: false},
    {field: "pictureTime", title: "创建时间", textAlign: 'center', sortable: false},

];

/**
 * 初始化表格定义
 */
var userDatatableSource = {
    init: function () {
        var params = {
            ifDelete: 'N',
            pictureType: 'HISTORICAL_DECETION'
        };
        userDatatable = $("#airportMaintenance_data").mDatatable(getMDatatableOption("list", params, tableColumns));
    },
    deleteById: function (ids) {
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '图片信息删除失败：',
            type: 'delete',
            url: basePath + '/picture/' + ids,
            success: function (json) {
                layer.msg('图片信息删除成功！', {
                    icon: 1, time: 1500
                }, function () {
                    userDatatable.reload();
                });
            }
        });
    },
    download: function (names) {
        var url = basePath + '/picture/downLoadPictures/' + names;
        downloadFile(url);
    }
};

function deleteByPrefixAndNo(id) {
    layer.confirm('确认删除吗?', {
        btn: ['yes', 'no'] //可以无限个按钮
        , yes: function () {
            $.hcPostAjax({
                url: basePath + "/picture/deleteById",
                data: {
                    'id': id

                },
                success: function () {
                    layer.msg('删除成功！', {
                        icon: 1, time: 1500
                    }, function () {
                        $("#m_search").click();
                    });
                }

            })


        }, btn2: function () {
            layer.msg('取消删除！', {
                icon: 1, time: 1500
            }, function () {
                $("#m_search").click();
            });
        }
    });
}


/**
 * 修改数据
 */
function EdiIt(id) {
    provinceId = id;
    msg = '编辑';
    openEditUser('修改图片名称', id);
}

/**
 * 新增和修改
 * @param title
 * @param obj
 */
function openEditUser(title, id) {

    var msg = isEmpty(id) ? "新增" : "编辑";

    layer.open({
        title: title,
        type: 1,
        maxmin: true,
        area: ['60%', '70%'],
        shadeClose: true,
        scrolling: false,
        content: $("#editHtml").html(),
        success: function (layero, index) {
            if (!isEmpty(id)) {
                renderFormData("#user-form", getDetail(id));
            }

            //保存
            $("#edit_yes").on("click", function () {
                times = 0;
                checkEvents();
                form.on('submit(save_airportmaintenance)', function (data) {
                    var param = getFormData("#user-form");
                    param.agentcode = $.trim($("select[name=agentcode]").val());
                    if (!isEmpty(id)) {
                        param.id = id;
                    } else {
                        param.password = $.trim($("input[name=password]").val());
                    }
                    $.hcPostAjax({
                        showLoad: true,
                        msgPrefix: msg + "出错：",
                        url: basePath + '/picture/updatePicture',
                        data: param,
                        success: function (data) {
                            layer.msg(msg + '成功！', {
                                icon: 1, time: 1500
                            }, function () {
                                userDatatable.reload();
                                layer.closeAll();
                                times = 0;
                                $("#m_search").click();
                            });
                        }
                    });
                });
            });
            //取消修改
            $("#edit_cancle").on("click", function () {
                layer.closeAll();
                times = 0;
            });
        }
    });
}

/**
 * 数据回显
 * @param id
 * @returns {*}
 */
function getDetail(id) {
    var oldData;
    $.hcPostAjax({
        type: 'get',
        url: basePath + "/picture/detail",
        data: {
            id: id
        },
        async: false,
        success: function (data) {
            oldData = data;
            return oldData;
        }
    });

}

/**
 * 表单校验
 */
function checkEvents() {
    form.verify({
        pictureName: [
            /[".jpg"]$/
            , '图片名称必须以result开头.jpg结尾'
        ]
    });
}